package com.example.keli.ui.userinfo;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.keli.R;
import com.example.keli.api.RetrofitManager;
import com.example.keli.base.App;
import com.example.keli.base.AppConfig;
import com.example.keli.base.BaseActivity;
import com.example.keli.base.app.C;
import com.example.keli.base.utils.AlbumUtil;
import com.example.keli.base.utils.DialogCall;
import com.example.keli.base.utils.DialogUtil;
import com.example.keli.base.utils.GlideUtil;
import com.example.keli.base.utils.LogUtils;
import com.example.keli.base.utils.SPUtils;
import com.example.keli.ui.my.model.UserInfo;
import com.flyco.roundview.RoundTextView;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.yanzhenjie.album.Action;
import com.yanzhenjie.album.AlbumFile;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import com.example.keli.api.http.api.BaseResponse;
import com.example.keli.api.http.api.subscriber.SubscriberListener;

/**
 * description: 设置
 * author: Allen
 * date: 2019/3/25 15:13
 */
public class SettingActivity extends BaseActivity {

    @BindView(R.id.avatar)
    ImageView avatar;
    @BindView(R.id.avatar_layout)
    RelativeLayout avatarLayout;
    @BindView(R.id.nick_name)
    TextView nickName;
    @BindView(R.id.nick_name_layout)
    RelativeLayout nickNameLayout;
    @BindView(R.id.quit)
    RoundTextView quit;

    public static void start(Context context) {
        Intent intent = new Intent(context, SettingActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int layoutId() {
        return R.layout.activity_setting;
    }

    @Override
    protected void bindData() {
        abTitle.setText("设置");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    ArrayList<AlbumFile> mAlbumFiles = new ArrayList<>();

    @OnClick({R.id.avatar_layout, R.id.nick_name_layout, R.id.quit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.avatar_layout:
                AlbumUtil.getImages(SettingActivity.this, 1, new Action<ArrayList<AlbumFile>>() {
                    @Override
                    public void onAction(@NonNull ArrayList<AlbumFile> result) {
                        uptokens(result.get(0).getPath());
                    }
                });
                break;
            case R.id.nick_name_layout:
                EditNameActivity.start(SettingActivity.this,nickName.getText().toString());
                break;
            case R.id.quit:
                DialogUtil.showDialog(SettingActivity.this, "提示", "确认退出登录吗？", new DialogCall() {
                    @Override
                    public void onPositive() {
                        SPUtils.clear(SettingActivity.this);
                        EventBus.getDefault().post(AppConfig.QUIT_LOGIN);
                        finish();
                    }

                    @Override
                    public void onNegative() {

                    }
                });
                break;
        }
    }

    private void getUserInfo() {
        Map<String, String> map = new HashMap<>();
        map.put("uid", App.getUid());
        map.put("page", "1");
        RetrofitManager.ApiFunc(RetrofitManager.mApiService.getUser(map), new SubscriberListener<BaseResponse<UserInfo>>() {
            @Override
            public void onSuccess(BaseResponse<UserInfo> listBaseResponse) {
                UserInfo userInfo = listBaseResponse.data;
                if (userInfo != null) {
                    GlideUtil.displayCircle(SettingActivity.this, avatar, userInfo.getAvatar());
                    nickName.setText(userInfo.getNickname());
                }
            }

            @Override
            public void onFailer(String msg) {
            }

            @Override
            public void onTokenError() {
            }
        });
    }

    private void uptokens(final String path) {
        startProgressDialog();
        RetrofitManager.ApiFunc(RetrofitManager.mApiFunc.uptokens(), new SubscriberListener<BaseResponse<String>>() {
            @Override
            public void onSuccess(BaseResponse<String> response) {
                Configuration config = new Configuration.Builder()
                        .dns(null)
                        .build();
                String key = String.valueOf(System.currentTimeMillis());
                UploadManager uploadManager = new UploadManager(config);
                uploadManager.put(path, key, response.getData(),
                        new UpCompletionHandler() {

                            @Override
                            public void complete(String key, ResponseInfo info, JSONObject res) {
                                //res包含hash、key等信息，具体字段取决于上传策略的设置
                                if (info.isOK()) {
                                    LogUtils.loge("qiniu", "Upload Success");
                                    String imageUrl = C.Constance.IMAGE_HOST + key + "?imageslim";
                                    setAvatar(imageUrl);
                                } else {
                                    LogUtils.loge("qiniu", "Upload Fail");
                                    //如果失败，这里可以把info信息上报自己的服务器，便于后面分析上传错误原因
                                }
                                stopProgressDialog();
                                LogUtils.loge(key + "地址.>>> " + info.path + ",你急吗>>>" + res.toString());
                                String fileName = "公司/存储/qiniu.jpg";
                                String domainOfBucket = "http://devtools.qiniu.com";
                                String finalUrl = String.format("%s/%s", domainOfBucket, fileName);
                                System.out.println(finalUrl);
                            }
                        }, null);
            }

            @Override
            public void onFailer(String msg) {
            }

            @Override
            public void onTokenError() {
            }
        });
    }

    private void setAvatar(final String path) {
        Map<String, String> map = new HashMap<>();
        map.put("avatar", path);
        RetrofitManager.ApiFunc(RetrofitManager.mApiFunc.setUser(map), new SubscriberListener<BaseResponse<Object>>() {
            @Override
            public void onSuccess(BaseResponse<Object> objectBaseResponse) {
                getUserInfo();
                EventBus.getDefault().post(C.EVENT.UPDATE_USERINFO);
            }

            @Override
            public void onFailer(String msg) {

            }

            @Override
            public void onTokenError() {

            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        getUserInfo();
    }
}
